import React, { PureComponent } from 'react';
import { message, Form, Input, Divider, Table, Icon, Button } from 'antd';
import { connect } from 'dva';
import SyOrderTableComponent from '../../components/SyOrderTableComponent';
import { SyOrderTableBasicFormComponent } from '../../components/SyOrderTableComponent';
import baseStyles from '../../components/SyOrderTableComponent/index.less';
import moment from 'moment';
import {env, host} from '../../utils/request';
import token from '../../utils/token';
import {sign} from '../../services/api';
import { stringify } from 'qs';


@Form.create()
@connect(state => ({
  modelState: state.withdrawBill,
}))
export default class WithdrawWaitToRepay extends SyOrderTableComponent {

  // 缺省
  _initSortion = { sortField: 'id', sortOrder: 'desc', };
  _initPagination = { pageSize: 20, current: 1, };
  _initCriteriaQuery = { status: 'wait-to-repay,partial-repayed' };
  _initSource = { source: 'up'};
  _initType = 'ranger'
  _operator = [

  ];

  initSelection() {
    const { dispatch } = this.props;
    dispatch({
      type: 'withdrawBill/fetchWaitRepayWithdrawCount',
      payload: {
        userName: '',
        mobile: '',
        withdrawId: '',
        startDate: '',
        endDate: ''
      }
    });
  }

  componentWillMount() {
    this.initSelection();
    this.setState({
      baseModel: 'withdrawBill',
      operator: this._operator,
      initPagination: this._initPagination,
      initSortion: this._initSortion,
      initCriteriaQuery: this._initCriteriaQuery,
      initType: this._initType,
      needSearch: true,
      needAdd: false,
      needEdit: false,
      needDelete: false,
      needTableColumnsOperator: false,
      needTableCheckbox: true,
      tableBorder: false,
      needTableStatistics: true,
      // defaultExpandAllRows: true,
      statusField: 'status',
      tableScroll: { y: 800 },
      tableColumns: [
        // {
        //   title: '用户ID',
        //   dataIndex: 'userId',
        //   width: 180,
        // },
        {
          title: '订单号',
          dataIndex: 'withdrawId',
          width: 180,
          fixed: 'left',
        },
        {
          title: '客户姓名',
          dataIndex: 'userName',
          width: 120,
          fixed: 'left',
        },
        {
          title: '性别',
          dataIndex: 'gender',
          width: 70,
          fixed: 'left',
        },
        {
          title: '手机号',
          dataIndex: 'mobile',
          width: 120,
          fixed: 'left',
        },
        {
          title: '申请时间',
          dataIndex: 'applyTime',
          width: 140,
          render: (text, record) => <span>{record.applyTime ? moment(record.applyTime).format('YYYY-MM-DD HH:mm') : '/'}</span>,
        },
        {
          title: '放款时间',
          dataIndex: 'startTime',
          width: 140,
          render: (text, record) => <span>{record.startTime ? moment(record.startTime).format('YYYY-MM-DD HH:mm') : '/'}</span>,
        },
        {
          title: '应还时间',
          dataIndex: 'endTime',
          width: 140,
          render: (text, record) => <span>{record.endTime ? moment(record.endTime).format('YYYY-MM-DD HH:mm') : '/'}</span>,
        },
        {
          title: '末次还款时间',
          dataIndex: 'repayTime',
          width: 140,
          render: (text, record) => <span>{record.repayTime ? moment(record.repayTime).format('YYYY-MM-DD HH:mm') : '/'}</span>,
        },
        {
          title: '周期',
          dataIndex: 'period',
          width: 80,
        },
        {
          title: '逾期天数',
          dataIndex: 'overdueLength',
          width: 90,
        },
        {
          title: '已还金额',
          dataIndex: 'repayAmount',
          width: 120,
          render: (text, record) => <span>￥ {record.repayAmount}</span>,
        },
        {
          title: '应还金额',
          dataIndex: 'remainAmount',
          width: 120,
          render: (text, record) => <span>￥ {record.remainAmount}</span>,
        },
        {
          title: '借款金额',
          dataIndex: 'withdrawAmount',
          width: 120,
          render: (text, record) => <span>￥ {record.withdrawAmount}</span>,
        },
        {
          title: '利息',
          dataIndex: 'interestAmount',
          width: 100,
          render: (text, record) => <span>￥ {record.interestAmount}</span>,
        },
        {
          title: '逾期利息',
          dataIndex: 'fineAmount',
          width: 90,
          render: (text, record) => <span>￥ {record.fineAmount}</span>,
        },
        // {
        //   title: '银行卡号',
        //   dataIndex: 'bankCardNum',
        //   width: 180,
        // },
        // {
        //   title: '所属银行',
        //   dataIndex: 'bankName',
        //   // width: 220,
        // },
        {
          title: '借款次数',
          dataIndex: 'withdrawTimes',
          // width: 100,
        },
        {
          title: '展期次数',
          dataIndex: 'extendCount',
        },
        {
          title: '代扣次数',
          dataIndex: 'withholdingCount',
          // width: 100,
        },
        {
          title: '操作',
          dataIndex: 'operatoer',
          width: 80,
          fixed: 'right',
          render: (text, record) =>
            <a onClick={() => {
              this.setState({ editedEntity: record });
              this.handleOperator(true, '还 款', this.billForm, null, this.renderBillForm, record, () => this.onRepayClick(record), null, this.renderBillModalFootButton, 1200)
            }}>
              还 款
           </a>,
        },
      ],
      searchFormItem: [
        {
          name: 'userName',
          label: '姓名',
          placeholder: '姓名',
          type: 'string',
        },
        {
          name: 'mobile',
          label: '手机号',
          placeholder: '手机号',
          type: 'string',
        },
        {
          name: 'withdrawId',
          label: '订单号',
          placeholder: '订单号',
          type: 'string',
        },
        {
          name: 'lendTime_n',
          label: '放款时间',
          type: 'ranger',
          showTime: false,
          onChange: (dateString)=>{console.log(dateString)}
        },
        {
          name: 'repayTime_n',
          label: '还款时间',
          type: 'ranger',
          showTime: false,
          onChange: (dateString)=>{}
        },
        {
          name: 'shouldTime_n',
          label: '到期应还时间',
          type: 'ranger',
          showTime: false,
          onChange: (dateString)=>{}
        },

      ],
      repayModalVisible: false,
      needFooterBtn: true,
      footerBtnConfig: [
        {
          buttonLabel: '代 扣',
          size: 'large',
          buttonType: 'danger',
          buttonIcon: 'none',
          buttonDisabled: 'none',
          needConfirm: true,
          okType: 'danger',
          okText: "确认",
          cancelText: "取消",
          confirmTitle: '代扣确认',
          handleEvent: () => {
            let withdrawIds = this.state.selectedRows.map(entity => entity.withdrawId);

            const { dispatch } = this.props;
            if (withdrawIds && withdrawIds.length > 0) {
              console.log(withdrawIds);
              dispatch({
                type: this.state.baseModel + '/fetchPostWithhold',
                payload: {
                  ids: withdrawIds,
                  source: 'up',
                },
                callback: (code, msg) => {
                  if (code == 200) {
                    message.success(msg);
                    this.resetCurrentForm();
                    dispatch({
                      type: this.state.baseModel + '/fetch',
                      payload: {
                        ...this.state.initPagination,
                        ...this.state.initSortion,
                        ...this.state.initCriteriaQuery,
                        ...this.state.statusQuery,
                        queryUrl: this.state.queryUrl,
                      }
                    });
                  } else {
                    message.error(msg);
                  }
                },
              });
            }
          },
        },
        {
          buttonLabel: '导  出',
          size: 'large',
          buttonType: 'primary',
          buttonIcon: 'none',
          needConfirm: false,
          handleEvent: () => {
            let senParam = {
              sortField: 'id',
              sortOrder: 'desc',
              pageSize: 20,
              current: 1,
              status: 'wait-to-repay,partial-repayed',
              source: 'up' ,
              lendStartDate: null,
              lendEndDate:  null,
              repayStartDate: null,
              repayEndDate:  null,
              startDate: null,
              endDate: null,
            }
            if(this.searchForm){
              const form = this.searchForm;
              form.validateFields((err, fieldsValue) => {
                if (err) return;
                if(this.handleDayDrun(fieldsValue.lendTime_n)){
                    message.info('时间范围在在90天内');
                    return;
                }
                if(this.handleDayDrun(fieldsValue.repayTime_n)){
                  message.info('时间范围在在90天内');
                  return;
                }
                if(this.handleDayDrun(fieldsValue.shouldTime_n)){
                  message.info('时间范围在在90天内');
                  return;
                }
                senParam.lendStartDate = fieldsValue.lendTime_n ? moment(fieldsValue.lendTime_n[0]).format('YYYY-MM-DD'): null;
                senParam.lendEndDate = fieldsValue.lendTime_n ? moment(fieldsValue.lendTime_n[1]).format('YYYY-MM-DD'): null;
                senParam.repayStartDate = fieldsValue.repayTime_n ? moment(fieldsValue.repayTime_n[0]).format('YYYY-MM-DD'): null;
                senParam.repayEndDate = fieldsValue.repayTime_n ? moment(fieldsValue.repayTime_n[1]).format('YYYY-MM-DD'): null;
                senParam.startDate = fieldsValue.shouldTime_n ? moment(fieldsValue.shouldTime_n[0]).format('YYYY-MM-DD'): null;
                senParam.endDate = fieldsValue.shouldTime_n ? moment(fieldsValue.shouldTime_n[1]).format('YYYY-MM-DD'): null;
                console.log(senParam)
                this.exportTable(senParam);
              });
            }else {
              this.exportTable(senParam);
            }

          },
        },
      ]
    });
  }


  handleDayDrun = (date) =>{
    if(!date) {
      return false
    }else {
      let releaseDate = moment(date[1]).format('YYYY-MM-DD').split('-');
      let currentDate = moment(date[0]).format('YYYY-MM-DD').split('-');
      let endDate = new Date(releaseDate[0], releaseDate[1]-1, releaseDate[2]);
      let  startDate= new Date(currentDate[0], currentDate[1]-1, currentDate[2]);
      const diff = parseInt(Math.abs(endDate - startDate ) / 1000 / 60 / 60 /24) + 1;
      if (diff>90){
        return true
      }else {
        return false
      }
    }
  }

  exportTable = (senParam) =>{
    var oReq = new XMLHttpRequest();
    oReq.open("GET", host[env] +'/bill/export/withdrawCenterListExport'+'?'+`${stringify(senParam)}`+'&sign='+sign(senParam), true);
    oReq.responseType = "blob";
    oReq.setRequestHeader("Content-Type","application/json");
    oReq.setRequestHeader('Authorization',token.get());
    oReq.onload = function (oEvent) {console.log(oEvent)
      var content = oReq.response;
      var elink = document.createElement('a');
      elink.download = '待还款列表.xls';//xlsx    因为后台输入是scv格式，用xlsx显示的不理想
      elink.style.display = 'none';
      var blob = new Blob([content]);
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      document.body.removeChild(elink);
    };
    oReq.send(JSON.stringify(senParam));
  }

  onRepayClick = (record) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'withdrawBill/queryRepayItemById',
      payload: { withdrawId: record.withdrawId },
    });
  }

  renderBillModalFootButton = [
    <Button key="forceRepay" type="danger" id='forceBtn' loading={this.props.modelState.operatorLoading}
            onClick={() => this.handleRepayClearEvent()}
      style={{ float: 'left' }}
    >
      强制结清
    </Button>,
    <Button key="repay" type="primary"  id='repayBtn' loading={this.props.modelState.operatorLoading}
            onClick={() => this.handleRepayEvent()}>
      还款
    </Button>,

  ];


  billFormItem = [
    {
      name: 'remainAmount',
      label: '应还金额',
      placeholder: '应还金额',
      type: 'readOnly',
      initValue: () => { return '￥ ' + this.state.editedEntity.remainAmount; },
      rules: [
        { required: true, message: '请输入还款金额', },
      ],
    },
    {
      name: 'repayAmount',
      label: '还款金额',
      placeholder: '还款金额',
      type: 'number',
      rules: [
        { required: true, message: '请输入还款金额', },
      ],
    },
    {
      name: 'repayTime',
      label: '还款时间',
      placeholder: '还款时间',
      type: 'dateTime',
      format: 'YYYY-MM-DD HH:mm:ss',
      showTime: true,
      initValue: moment(new Date(), 'YYYY-MM-DD HH:mm:ss'),
      rules: [{
        required: true, message: '请选择还款时间',
      }],
    },
    {
      name: 'remark',
      label: '备注',
      placeholder: '备注',
      type: 'longString',
    },
  ];

  renderBillForm = () => {
    const { form, modelState: { selectItems } } = this.props;
    return (
      <SyOrderTableBasicFormComponent
        ref={this.saveBillFormFormRef}
        formItems={this.billFormItem}
        selectItems={selectItems}
        renderAppend={this.renderRepayModalAppend}
      >
      </SyOrderTableBasicFormComponent>
    );
  }

  saveBillFormFormRef = (form) => {
    this.billForm = form;
  }

  renderRepayModalAppend = () => {
    return (
      <div>
        <Table
          scroll={{ y: 300 }}
          dataSource={this.props.modelState.currRepayItem}
          columns={this.repayModelRepayColumns}
          pagination={false}
          size='small'
          loading={this.props.modelState.repayItemLoading}
          title={() => {
            return (
              <span style={{ fontWeight: 'bold', fontSize: 16 }}>
                还款记录
              </span>
            );
          }}
          rowKey={record => record.key}
        />
      </div>
    );
  }

  repayModelRepayColumns = [
    {
      title: '还款日期',
      dataIndex: 'repayTime',
      width: 150,
      align: 'center',
      render: (text, record) => <span>{moment(record.repayTime).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '还款金额',
      dataIndex: 'repayAmount',
      width: 150,
      align: 'center',
      render: (text, record) => <span>￥ {record.repayAmount}</span>,
    },
    {
      title: '操作时间日期',
      dataIndex: 'createTime',
      width: 150,
      align: 'center',
      render: (text, record) => <span>{moment(record.createTime).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
  ];


  handleRepayEvent = (e) => {
    const { dispatch } = this.props;
    const form = this.billForm;
    const { editedEntity } = this.state;
    document.getElementById('repayBtn').setAttribute('disabled',true);
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if (fieldsValue.repayAmount > editedEntity.remainAmount) {
        document.getElementById('repayBtn').removeAttribute('disabled');
        form.setFields({
          repayAmount: {
            value: fieldsValue.repayAmount,
            errors: [new Error('还款金额不能大于剩余应还金额'),]
          }
        });
        return;
      }

      let value = {
        withdrawId: editedEntity.withdrawId,
        repayAmount: fieldsValue.repayAmount,
        repayTime: moment(fieldsValue.repayTime).format('YYYY-MM-DD HH:mm:ss'),
      };
      if (fieldsValue.remark && fieldsValue.remark.length > 0) {
        value.remark = fieldsValue.remark;
      }

      dispatch({
        type: this.state.baseModel + '/addRepayItem',
        payload: { ...value },
        callback: (code, msg) => {
          document.getElementById('repayBtn').removeAttribute('disabled');
          if (code == 200) {
            message.success(msg);
            this.resetCurrentForm();
            dispatch({
              type: this.state.baseModel + '/fetch',
              payload: {
                ...this.state.initPagination,
                ...this.state.initSortion,
                ...this.state.initCriteriaQuery,
                ...this.state.statusQuery,
                queryUrl: this.state.queryUrl,
              }
            });
          } else {
            message.error(msg);
          }
        },
      });
    });
  }


  handleRepayClearEvent = (e) => {
    const { dispatch } = this.props;
    const form = this.billForm;
    const { editedEntity } = this.state;
    document.getElementById('forceBtn').setAttribute('disabled',true);
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if (fieldsValue.repayAmount > editedEntity.remainAmount) {
        document.getElementById('forceBtn').removeAttribute('disabled');
        form.setFields({
          repayAmount: {
            value: fieldsValue.repayAmount,
            errors: [new Error('还款金额不能大于剩余应还金额'),]
          }
        });
        return;
      }

      let value = {
        withdrawId: editedEntity.withdrawId,
        repayAmount: fieldsValue.repayAmount,
        repayTime: moment(fieldsValue.repayTime).format('YYYY-MM-DD HH:mm:ss'),
      };
      if (fieldsValue.remark && fieldsValue.remark.length > 0) {
        value.remark = fieldsValue.remark;
      } else {
        form.setFields({
          remark: {
            value: fieldsValue.remark,
            errors: [new Error('强制结清必须填写备注'),]
          }
        });
        return;
      }

      dispatch({
        type: this.state.baseModel + '/addRepayItemClear',
        payload: { ...value },
        callback: (code, msg) => {
          document.getElementById('repayBtn').removeAttribute('disabled');
          if (code == 200) {
            message.success(msg);
            this.resetCurrentForm();
            dispatch({
              type: this.state.baseModel + '/fetch',
              payload: {
                ...this.state.initPagination,
                ...this.state.initSortion,
                ...this.state.initCriteriaQuery,
                ...this.state.statusQuery,
                queryUrl: this.state.queryUrl,
              }
            });
          } else {
            message.error(msg);
          }
        },
      });
    });
  }


  /* ***************************************************************** */

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    super.componentDidMount();
  }

}
